package com.ntschy.taizhou.threaddemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

// 批量同时执行多个任务,由串行改为并行. 缩短了任务执行时间. 单个任务是5秒,100次, 总时间由500秒减少到75秒.
public class FutureTest3 {

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        UserInfoService userInfoService = new UserInfoService();
        MedalService medalService = new MedalService();
        long userId = 666L;
        long startTime = System.currentTimeMillis();
        List<CompletableFuture<UserInfo>> futureList = new ArrayList<>(); // 并发处理结果集
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add(1);
        }
        for (int i = 0; i < list.size(); i++) {
            //调用用户服务获取用户基本信息
            CompletableFuture<UserInfo> completableUserInfoFuture = CompletableFuture.supplyAsync(() -> {
                try {
                    UserInfo userInfo = userInfoService.getUserInfo(userId);
                    return userInfo;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            });
            futureList.add(completableUserInfoFuture);
        }
        for (CompletableFuture<UserInfo> userInfoCompletableFuture : futureList) {
            UserInfo userInfo = userInfoCompletableFuture.get();
            System.out.println(userInfo);
        }
        //   UserInfo userInfo = completableUserInfoFuture.get();//获取个人信息结果
        //MedalInfo medalInfo = completableMedalInfoFuture.get();//获取勋章信息结果
        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    }

}
